﻿using LSFTP;
using LSFTP.model;
using LSFTP.MultithreadFileDownload;
using LSFTP.MultithreadFileUpload;
using Rainbow.core;
using Rainbow.model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;

namespace Rainbow.view
{
    /// <summary>
    /// DownloadFileDlg.xaml 的交互逻辑
    /// </summary>
    public partial class UploadFileDlg : Window
    {
        private UploadFileDlgViewModel windowViewModel;

        private UpLoadFile dlf;

        private SFTPClient sftp;

        //private string remotePath;
        //private string localPath;
        //private List<string> localFiles;
        private List<string[]> files;

        public UploadFileDlg()
        {
            InitializeComponent();

            dlf = new UpLoadFile();
            dlf.ThreadNum = TW_App.globalSetting.uploadThreadNum;
            dlf.doSendMsg += UpdateListView;

            this.Loaded += new RoutedEventHandler(Window_Loaded);

            this.btnOK.Click += new RoutedEventHandler(OK_Click);
            this.btnCancel.Click += new RoutedEventHandler(Cancel_Click);

            windowViewModel = new UploadFileDlgViewModel();
            this.DataContext = windowViewModel;
        }

        public UploadFileDlg(List<string[]> files, SFTPClient sftp) : this()
        {
            this.sftp = sftp;
            this.files = files;

            this.btnOK.IsEnabled = false;
        }


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            StartUp();
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            if(windowViewModel.finishCount == windowViewModel.totalCount)
            {
                this.DialogResult = true;
            }
            else
            {
                MessageBoxResult result = System.Windows.MessageBox.Show("上传未完成，是否确认停止上传","提示",MessageBoxButton.YesNo,MessageBoxImage.Question);
                if(MessageBoxResult.Yes == result)
                {
                    dlf.StopUp();
                    this.DialogResult= false;
                }
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            if (windowViewModel.finishCount == windowViewModel.totalCount)
            {
                this.DialogResult = true;
            }
            else
            {
                MessageBoxResult result = System.Windows.MessageBox.Show("上传未完成，是否确认停止上传", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (MessageBoxResult.Yes == result)
                {
                    dlf.StopUp();
                    this.DialogResult = false;
                }
            }
        }

        private void StartUp()
        {
            try
            {
                files.ForEach(file =>
                {
                    UploadFileInfoViewModel uploadFileInfoViewModel = new UploadFileInfoViewModel();
                    uploadFileInfoViewModel.localPath = file[1];
                    uploadFileInfoViewModel.remotePath = file[2];
                    uploadFileInfoViewModel.name = file[0];
                    uploadFileInfoViewModel.index = windowViewModel.infos.Count + 1;
                    windowViewModel.infos.Add(uploadFileInfoViewModel);
                });        


                windowViewModel.totalCount = windowViewModel.infos.Count;
                foreach (var item in windowViewModel.infos)
                {
                    dlf.AddUp(item.remotePath, item.localPath, sftp, item.index - 1);
                }
                dlf.StartUp(dlf.ThreadNum);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SFTP文件获取失败，原因：{0}", ex.Message));
            }
        }


        private void UpdateListView(UpMsg msg)
        {
            switch (msg.Tag)
            {
                case UpStatus.Start:
                    App.Current.Dispatcher.InvokeAsync((Action)(() =>
                    {
                        windowViewModel.infos[msg.Id].status = "开始上传";
                        windowViewModel.infos[msg.Id].dateTime = DateTime.Now;
                    }));
                    break;
                case UpStatus.GetLength:
                    App.Current.Dispatcher.InvokeAsync((Action)(() =>
                    {
                        windowViewModel.infos[msg.Id].status = "连接成功";
                        windowViewModel.infos[msg.Id].totalSize = msg.LengthInfo;
                    }));
                    break;
                case UpStatus.End:
                case UpStatus.UpLoad:
                    App.Current.Dispatcher.InvokeAsync((Action)(() =>
                    {
                        windowViewModel.infos[msg.Id].completed = msg.SizeInfo;
                        windowViewModel.infos[msg.Id].progress = (int)msg.Progress;
                        windowViewModel.infos[msg.Id].speed = msg.SpeedInfo;
                        windowViewModel.infos[msg.Id].residue = msg.SurplusInfo;
                        if (msg.Tag == UpStatus.UpLoad)
                        {
                            windowViewModel.infos[msg.Id].status = "上传中";
                        }
                        else
                        {
                            windowViewModel.infos[msg.Id].status = "上传完成";
                            windowViewModel.finishCount++;
                            if(windowViewModel.finishCount == windowViewModel.totalCount)
                            {
                                this.btnOK.IsEnabled = true;
                            }
                            if (windowViewModel.finishCount > windowViewModel.totalCount)
                            {
                                windowViewModel.finishCount = windowViewModel.totalCount;
                            }
                        }
                    }));
                    break;
                case UpStatus.Error:
                    App.Current.Dispatcher.InvokeAsync((Action)(() =>
                    {
                        windowViewModel.infos[msg.Id].residue = "失败";
                        windowViewModel.infos[msg.Id].status = msg.ErrMessage;
                    }));
                    break;
            }
        }
    }

    public class UploadFileDlgViewModel : ViewModelBase
    {
        public UploadFileDlgViewModel()
        {
            totalCount = 0;
            finishCount = 0;
            infos = new ObservableCollection<UploadFileInfoViewModel>();
        }

        private ObservableCollection<UploadFileInfoViewModel> m_infos;
        public ObservableCollection<UploadFileInfoViewModel> infos
        {
            get { return m_infos; }
            set
            {
                m_infos = value;
                NotifyPropertyChanged();
            }
        }

        private int m_finishCount;
        public int finishCount
        {
            get { return m_finishCount; }
            set
            {
                m_finishCount = value;
                NotifyPropertyChanged();
            }
        }

        private int m_totalCount;
        public int totalCount
        {
            get { return m_totalCount; }
            set
            {
                m_totalCount = value;
                NotifyPropertyChanged();
            }
        }
    }
}
